#!/bin/bash

. base.sh

ROS_DEPS=${OUTPUT}/ros-deps.list
ROS_DEPS_SRC=${OUTPUT}/ros-deps-src.list

# Default values
specific_pkg=""

usage()
{
    info_log "Usage: $0 [options]"
    info_log "Options:"
    info_log "  -p, --package <package_name>    Analyze specific package only"
    info_log "  -h, --help                      Show this help message"
    exit 1
}

prepare()
{
	if [ ! -d ${ROS_DEPS_BASE} ]
	then
		_log ${LOG_LEVEL_ERROR} "Can not find ${ROS_DEPS_BASE}, you can use get-pkg-deps.sh to create it"
		exit 1
	fi

	cat /etc/os-release | grep -q Ubuntu
	if [ $? -ne 0 ]
	then
		_log ${LOG_LEVEL_ERROR} "Please run me in Ubuntu system"
		exit 1
	fi

	>${ROS_DEPS}
	>${ROS_DEPS_SRC}
}

analyze_package()
{
    local pkg=$1
    local apt_result="${ROS_OUTPUT_TMP}/.apt_result_${pkg}"
    
    info_log "Analyse $pkg"
    echo -e "$pkg" >> ${ROS_DEPS}

    # 使用临时文件存储apt结果
    apt show $pkg 2>/dev/null >${apt_result}
    if [ $? -ne 0 ]; then
        error_log "Can not find pkg $pkg"
        echo $pkg >>${ROS_DEPS_SRC}
        rm -f ${apt_result}
        return
    fi

    src_pkg=$(grep "Source: " ${apt_result} | awk -F "Source: " '{print $2}')
    rm -f ${apt_result}
    
    if [ "$src_pkg" = "" ]; then
        src_pkg=$pkg
        debug_log "No source package found for $pkg, using package name as source"
    fi

    echo -e "$pkg\t$src_pkg" >> ${ROS_DEPS_SRC}
}

main()
{
	# Parse command line arguments
	while [[ $# -gt 0 ]]; do
		case $1 in
			-p|--package)
				specific_pkg="$2"
				shift 2
				;;
			-h|--help)
				usage
				;;
			*)
				echo "Unknown option: $1"
				usage
				;;
		esac
	done

	prepare

	_log ${LOG_LEVEL_INFO} "Start to analyse ros-pkg."

	if [ -n "$specific_pkg" ]; then
		# Analyze specific package
		for pkg in `cat ${ROS_DEPS_BASE}/${specific_pkg}-ExtDeps 2>/dev/null`; do
			analyze_package "$pkg"
		done
	else
		# Analyze all packages
		for i in `cat ${ROS_DEPS_BASE}/*ExtDeps | sort | uniq`; do
			analyze_package "$i"
		done
	fi

	_log ${LOG_LEVEL_INFO} "Gen ros-pkg-src.list done, you can find it in ${ROS_DEPS_SRC}"
}

main "$@"
